/**
 * 文本加载
 * @author zzhanglin
 */
URLLoader = function()
{
	EventDispatcher.call(this);
	this.className="URLLoader";
	this.dataFormate = "text"; //默认为URLLoaderDataFormat.TEXT
	this.timeout = 10000 ;//超时时间，默认为10秒钟

	this._data ;
	this._timeoutId ;
	this._xmlhttp;
};
FLASH.extend(URLLoader,EventDispatcher); 

//获取数据
URLLoader.prototype.getData = function(){ return this._data ;} ;

/**
 * 加载文本
 */
URLLoader.prototype.load = function(urlRequest)
{
	if (window.XMLHttpRequest)
    {
		this._xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
    }else{
    	this._xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
    }
	
	var _self = this ;
	if(this._xmlhttp)
	{
		this._xmlhttp.onreadystatechange=function()
	    {
			if (_self._xmlhttp.readyState!=4) return;

		    if (_self._xmlhttp.status==200)
		    {
		    	_self._data = _self._xmlhttp.responseText ;
		    	_self._complete();
		    	_self._xmlhttp = null ;
		    	clearTimeout(_self.timeoutId) ;
		    	this._timeoutId =0;
		    }else{
		    	_self._ioError("请求失败",_self._xmlhttp.status);
		    	_self._xmlhttp = null ;
		    	clearTimeout(_self.timeoutId) ;
		    	this._timeoutId =0;
		    }
	    };
	    if(urlRequest.method=URLRequestMethod.POST){
			this._xmlhttp.open(urlRequest.method,urlRequest.url,true);
			this._xmlhttp.setRequestHeader("Content-type",  urlRequest.contentType);
			this._xmlhttp.send(urlRequest.toString());
		}else{
			this._xmlhttp.open(urlRequest.method,urlRequest.toString(),true);
			this._xmlhttp.setRequestHeader("Content-type",  urlRequest.contentType);
			this._xmlhttp.send();
		}
		
		
		this._open();
		this._timeoutId = setTimeout(timeoutHandler , _self.timeout);
		function timeoutHandler(){
			clearTimeout(_self.timeoutId) ;
	    	this._timeoutId =0;
			_self.close();
		}
	}
};

/**
 * 停止加载
 */
URLLoader.prototype.close = function()
{
	if(this._xmlhttp) this._xmlhttp.abort();
};

/**
 * 释放资源
 */
URLLoader.prototype.dispose =function()
{
	EventDispatcher.prototype.dispose.call(this);
	if(this._timeoutId>0)
		clearTimeout(this._timeoutId);
	this._data  = null ;
	this._xmlhttp = null ;
};

//=======私有方法==============================
/**
 * 完成后抛出Event.COMPLETE事件
 */
URLLoader.prototype._complete = function()
{
	this.dispatchEvent( new Event(Event.COMPLETE) );
};


URLLoader.prototype._open = function()
{
	this.dispatchEvent( new Event(Event.OPEN) );
};

URLLoader.prototype._ioError = function(text,id)
{
	this.dispatchEvent( new IOErrorEvent(IOErrorEvent.IO_ERROR, text, id) );
};
